package fgoScript.service;

import commons.entity.Constant;
import commons.util.GameUtil;
import commons.util.PropertiesUtil;
import fgoScript.constant.GameConstant;
import fgoScript.constant.PointInfo;
import fgoScript.entity.CardComparator;
import fgoScript.entity.CommonCard;
import fgoScript.entity.PointColor;
import fgoScript.exception.AppNeedRestartException;
import fgoScript.exception.AppNeedStopException;
import org.apache.logging.log4j.Logger;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.*;
import java.util.List;

public class CommonMethods {

	public static PointColor open2GudaOrRestart() throws Exception {
        // 公告×点
		Point p_notice_exit = PointInfo.getInstance().getpNoticeExit();
		Color c_notice_exit = PointInfo.getInstance().getcNoticeExit();
		// 公告×点
		Point p_notice_exit_dark = PointInfo.getInstance().getpNoticeExitDark();
		Color c_notice_exit_dark = PointInfo.getInstance().getcNoticeExitDark();
		// 盲点
		Point dead_point = PointInfo.getInstance().getDeadPoint();
		// 咕哒子
		Point p_guda = PointInfo.getInstance().getpGuda();
		Color c_guda = PointInfo.getInstance().getcGuda();
		// 引继页面
		Point p_transfer = new Point(911, 670);// 颜色：0;60;165
		Color c_transfer = new Color(6, 64, 163);
		// 再开按钮（是）
		Point p_button_restart_yes = PointInfo.getInstance().getpButtonRestartYes();
		Color c_button_restart_yes = PointInfo.getInstance().getcButtonRestartYes();
		//新加入点
		List<PointColor> open2GudaList = PointInfo.getInstance().getOpen2GudaList();
		List<PointColor> beforeFinishGudaList = PointInfo.getInstance().getBeforeFinishGudaList();
		List<PointColor> pcList = new ArrayList<>();
		int ogSize = open2GudaList.size();
		//遍历加入点
		for (int i = 0; i < ogSize; i++) {
			pcList.add(open2GudaList.get(i));
		}
		pcList.add(new PointColor(p_notice_exit, c_notice_exit, p_notice_exit, true));
		pcList.add(new PointColor(p_notice_exit_dark, c_notice_exit_dark, p_notice_exit_dark, true));
		pcList.add(new PointColor(p_transfer, c_transfer, PointInfo.getInstance().getDeadPoint(), true));
		pcList.add(new PointColor(p_button_restart_yes, c_button_restart_yes, p_button_restart_yes, true));
		List<PointColor> finishPCList = new ArrayList<>();
		finishPCList.add(new PointColor(p_guda, c_guda, dead_point, true));
		PointColor pcRestart = new PointColor(p_button_restart_yes, c_button_restart_yes, p_button_restart_yes, true);
		pcRestart.setConfirm(true);
		finishPCList.add(pcRestart);

		AutoAct ac = new AutoAct(pcList, finishPCList,beforeFinishGudaList) {
			@Override
			public void doSomeThing() {
			}
		};
		ac.autoAct();
		return ac.getPcWait();
    }
	public static boolean[] attackBAAForEvent(boolean goMainNP, boolean[] hases, Logger LOGGER) throws Exception {
		Point pNp01 = PointInfo.getInstance().getNpCheck();
		Point pNp02 = new Point((int)pNp01.getX()+ GameConstant.HEAD_SPACE, (int)pNp01.getY());
		Point pNp03 = new Point((int)pNp01.getX()+ GameConstant.HEAD_SPACE*2, (int)pNp01.getY());
		Color cNp01 = GameUtil.getScreenPixel(pNp01);
		Color cNp02 = GameUtil.getScreenPixel(pNp02);
		Color cNp03 = GameUtil.getScreenPixel(pNp03);
		int rgb01 = cNp01.getRGB();
		int rgb02 = cNp02.getRGB();
		int rgb03 = cNp03.getRGB();
		Color cNp01_Delay = GameUtil.getScreenPixel(pNp01);
		Color cNp02_Delay = GameUtil.getScreenPixel(pNp02);
		Color cNp03_Delay = GameUtil.getScreenPixel(pNp03);
		int rgb01_Delay = cNp01_Delay.getRGB();
		int rgb02_Delay = cNp02_Delay.getRGB();
		int rgb03_Delay = cNp03_Delay.getRGB();
		boolean has = rgb01 != rgb01_Delay
				|| rgb02 != rgb02_Delay
				|| rgb03 != rgb03_Delay;
		int npCount = 0;
		boolean hasNp01 = rgb01 != rgb01_Delay;
		boolean hasNp02 = rgb02 != rgb02_Delay;
		boolean hasNp03 = rgb03 != rgb03_Delay;
		LOGGER.info("有宝具吗？  " + (has));
		if ( has ) {
			// 等待
			waitToAttack(null, LOGGER);
			// 蓝色圆板选择
			blueAttackSelect();
			// 开始点击卡片
			Map<String, List<CommonCard>> scMap;
			if (hasNp01 && goMainNP) {
				scMap = getWeakCommondCards(CardComparator.getRgbComparotor(),LOGGER);
			}else {
				scMap = getWeakCommondCards(CardComparator.getBgrComparotor(),LOGGER);
			}
			Point np_np01 = PointInfo.getInstance().getNpNp();
			Point np_np02 = new Point((int) np_np01.getX()+GameConstant.NP_SPACE,(int) np_np01.getY());
			Point np_np03 = new Point((int) np_np01.getX()+GameConstant.NP_SPACE*2,(int) np_np01.getY());
			if (hasNp03) {
				// 宝具
				GameUtil.getMymouse().mouseMoveByPoint(np_np03,true,true);

				GameUtil.getMymouse().mousePressAndRelease(GameConstant.DELAY/6);
				npCount++;
			}
			if (hasNp02) {
				// 宝具
				GameUtil.getMymouse().mouseMoveByPoint(np_np02,true,true);

				GameUtil.getMymouse().mousePressAndRelease(GameConstant.DELAY/6);
				npCount++;
			}
			if (hasNp01 && goMainNP) {
				// 宝具
				GameUtil.getMymouse().mouseMoveByPoint(np_np01,true,true);

				GameUtil.getMymouse().mousePressAndRelease(GameConstant.DELAY/6);
				npCount++;
			}
			List<CommonCard> trueList = scMap.get("trueList");
			List<CommonCard> falseList = scMap.get("falseList");
			int size = trueList.size();
			for (int j = 0; j < size; j++) {
				GameUtil.getMymouse().mouseMoveByPoint(trueList.get(j).getpLoc(),true,true);

				GameUtil.getMymouse().mousePressAndRelease(GameConstant.DELAY/6);
			}
			if (size < (3-npCount)) {
				int num = 2-trueList.size()+1;
				for (int j = 0; j < num; j++) {
					GameUtil.getMymouse().mouseMoveByPoint(falseList.get(j).getpLoc(),true,true);

					GameUtil.getMymouse().mousePressAndRelease(GameConstant.DELAY/6);
				}
			}
		} else {
			attackNPAAA(LOGGER);
		}
		checkExitCardSelect();
		return hases;
	}
	/**
	 * 等待攻击（蓝色）
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public static PointColor waitToAttack(String str, Logger LOGGER) throws Exception {
		if (str != null) {
			LOGGER.info("等待（ " + str + " ）回合蓝盾攻击：");
		}

		List<PointColor> pocoList = new ArrayList<PointColor>();
		pocoList.add(new PointColor(PointInfo.getInstance().getpBlueAttack(), PointInfo.getInstance().getcBlueAttack(), true, "attack"));
		pocoList.add(new PointColor(PointInfo.getInstance().getpFetter01(), PointInfo.getInstance().getcFetter01(), true, "balance"));
		pocoList.add(new PointColor(PointInfo.getInstance().getpFetter02(), PointInfo.getInstance().getcFetter02(), true, ""));
		pocoList.add(new PointColor(PointInfo.getInstance().getpFetter03(), PointInfo.getInstance().getcFetter03(), true, ""));
		pocoList.add(new PointColor(PointInfo.getInstance().getpFetterUp(), PointInfo.getInstance().getcFetterUp(), true, ""));
		pocoList.add(new PointColor(PointInfo.getInstance().getpLevelUp(), PointInfo.getInstance().getcLevelUp(), true, ""));
		pocoList.add(new PointColor(PointInfo.getInstance().getpConfirmRd(), PointInfo.getInstance().getcConfirmRd(), true, ""));
		PointColor pc = GameUtil.waitUntilOneColor(pocoList, Constant.FGOMonitor);
		return pc;
	}
	public static void blueAttackSelect() throws AppNeedRestartException, AppNeedStopException {
		Point p_card_exit = PointInfo.getInstance().getpCardExit();
		Color c_card_exit = PointInfo.getInstance().getcCardExit();
		PointColor pc = new PointColor(p_card_exit, c_card_exit, true);
		Point p5 = new Point(1171, 697);
		GameUtil.getMymouse().mouseMoveByPoint(p5,true,true);

		GameUtil.getMymouse().mousePressAndReleaseForConfirm(null);
		// 宝具动画延时
		GameUtil.delay(GameConstant.DELAY * 4);
	}
	public static Map<String, List<CommonCard>> getWeakCommondCards(Comparator<CommonCard> comp, Logger LOGGER){
		List<CommonCard> ccList = getColorCommondCards();
		Collections.sort(ccList, comp);
		Map<String, List<CommonCard>> scMap = new HashMap<>();
		List<CommonCard> trueList = new ArrayList<CommonCard>();
		List<CommonCard> falseList = new ArrayList<CommonCard>();
		int num = ccList.size();
		for (int i = 0; i < num; i++) {
			CommonCard commonCard = ccList.get(i);
			LOGGER.info(commonCard.getCardColor() + "_");
			LOGGER.info(commonCard.isWeak());
			if (commonCard.isWeak()==true) {
				trueList.add(commonCard);
			}else {
				falseList.add(commonCard);
			}
		}
		scMap.put("trueList", trueList);
		scMap.put("falseList", falseList);
		return scMap;
	}
	public static void attackNPAAA(Logger LOGGER)  throws Exception{
		attackAAA(CardComparator.getBgrComparotor(), LOGGER);
	}
	public static void attackAAA(Comparator<CommonCard> comp, Logger LOGGER) throws Exception {
		// 蓝色圆板
		Point p0 = new Point(1171, 697);// 颜色：0;113;216 Color c1 = new Color(0, 113, 216);
		GameUtil.getMymouse().mouseMoveByPoint(p0,true,true);

		GameUtil.getMymouse().mousePressAndRelease(GameConstant.DELAY/6);
		// 等待一会儿
		GameUtil.delay(GameConstant.DELAY * 4);
		Map<String, List<CommonCard>> scMap = getWeakCommondCards(comp, LOGGER);
		List<CommonCard> trueList = scMap.get("trueList");

		int size = trueList.size();
		for (int i = 0; i < 3; i++) {
			GameUtil.getMymouse().mouseMoveByPoint(trueList.get(i).getpLoc(),true,true);

			GameUtil.getMymouse().mousePressAndRelease(GameConstant.DELAY/6);

		}
		checkExitCardSelect();
	}
	public static List<CommonCard> getColorCommondCards(){
		String  zeroPosition =  PropertiesUtil.getValueFromCommandCardFile("zeroPosition");
		String  clickPosition =  PropertiesUtil.getValueFromCommandCardFile("clickPosition");
		String  distribution =  PropertiesUtil.getValueFromCommandCardFile("distribution");
		Point[] zeroPoints = getPointsBySymBol(zeroPosition);// 每张卡的 原点 数组
		Point[] clickPoints = getPointsBySymBol(clickPosition);// 每张卡的 点击点 数组
		Point[] distributionPoints = getPointsBySymBol(distribution);// 一张卡的 颜色分布取点 数组

		int zpLen = zeroPoints.length;
		int cpLen = clickPoints.length;
		int dtLen = distributionPoints.length;

		Point tempPoint;
		Color tempColor;

		int rPulus = 0;
		int gPulus = 0;
		int bPulus = 0;
		int[] rgb;
		int rgblen;
		List<CommonCard> ccList= new ArrayList<>();
		CommonCard tempCommonCard;

		int Maxindex;
		int value;
		for (int i = 0; i < zpLen; i++) {
			rgb = new int[3];
			for (int j = 0; j < dtLen; j++) {
				tempPoint = new Point(
						(int) (zeroPoints[i].getX() + distributionPoints[j].getX()),
						(int) (zeroPoints[i].getY() + distributionPoints[j].getY())
				);
				tempColor = GameUtil.getScreenPixel(tempPoint);
				rgb[0] += tempColor.getRed();
				rgb[1] += tempColor.getGreen();
				rgb[2] += tempColor.getBlue();
			}
			rgblen = rgb.length;
			Maxindex = 0;
			value = rgb[0];
			for (int j = 1; j < rgblen; j++) {
				if (value < rgb[j]) {
					Maxindex = j;
					value = rgb[j];
				}
			}
			tempCommonCard = new CommonCard();
			tempCommonCard.setpLoc(clickPoints[i]);
			tempCommonCard.setWeak(true);
			switch(Maxindex){
				case 0 : {
					tempCommonCard.setCardColor(GameConstant.RED);
					break;
				}
				case 1 : {
					tempCommonCard.setCardColor(GameConstant.GREEN);
					break;
				}
				case 2 : {
					tempCommonCard.setCardColor(GameConstant.BLUE);
					break;
				}
				default : {
					break;
				}
			}
			ccList.add(tempCommonCard);
		}
		return ccList;
	}
	public static void checkExitCardSelect() throws AppNeedRestartException, AppNeedStopException {
		GameUtil.delay(GameConstant.DELAY * 5);
		Point p = PointInfo.getInstance().getpCardExit();
		Color c = PointInfo.getInstance().getcCardExit();
		Color temp = GameUtil.getScreenPixel(p);
		boolean isColor = GameUtil.likeEqualColor(c, temp);
		if (isColor) {
			GameUtil.getMymouse().mouseMoveByPoint(p,true,true);

			GameUtil.getMymouse().mousePressAndReleaseForConfirm(null);
		}
	}
	public static Point[] getPointsBySymBol(String string){
		String[] pointStringArray = string.split("_");
		int len = pointStringArray.length;

		String[] tempStringArray;
		Point[] points = new Point[len];

		for (int i = 0; i < len; i++) {
			tempStringArray = pointStringArray[i].split(",");
			points[i] = new Point(
					Integer.parseInt(tempStringArray[0]),
					Integer.parseInt(tempStringArray[1])
			);
		}
		return points;
	}

}
